<?php

namespace Logic\User;

use Core\Exception;
use Validator\UserValidator;
use think\Db;
use Helper\NetworkHelper;
use Service\YarService;
use Helper\StringHelper;
/**
 * 用户权限相关服务
 * Class UserLogic
 * @package Logic\User
 */
class AuthLogic
{


    /**
     * 登录操作
     * @param $mobile
     * @param $password
     * @param $platform (1电脑端 2移动端 3微信 4安卓 5苹果)
     * @throws
     */
    public function login($mobile, $password, $platform,$appType='')
    {
        $rules = [
            'mobile' => 'isPhone',
            'password' => 'require'
        ];
        $validator = new UserValidator();
        $validator->validate(compact('mobile', 'password'), $rules);
        $mUser = new \UserModel();
        $userCheck =$mUser->checkLogin($mobile, $password);
        if (empty($userCheck['id'])){
            throw new Exception(10114);
        }

        //卖家版拦截操作
        if ($appType == 'SELLER'){
            //允许登录的身份
            $enableSignRole = [
                'REGISTER',
                'ORD_BUYER',
                'ORD_SELLER',
                'SUPPLIER'
            ];
            $UserRole = new \mtyUser\UserRole();
            $userRole = $UserRole->getUserRole($userCheck['id'])['data'];
            if (count(array_intersect($userRole,$enableSignRole))<1){
                throw new Exception(10147);
            }
        }

        // 写入日志
        Db::name('user_login_log')->insert([
            'userid' => $userCheck['id'],
            'platform' => $platform,
            'logindate'=> date('Y-m-d'),
            'ip' => $_SERVER['REMOTE_ADDR'],
            'method' => 1,
            'addtime' => time()
        ]);

        return $userCheck;
    }

    /**
     * 注册服务
     * @param $params
     * @return mixed
     * @throws
     */
    public function register($params = [])
    {
        $params['unionid']  = $params['unionid'] ?: '';
        $params['method']  = $params['method'] ?: '';
        $params['refferee']  = $params['refferee'] ?: '';
        $params['platform']  = $params['platform'] ?: 3;
        $rules = [
            'mobile'    => 'require|isPhone',
            'password'  => 'require|length:6,18',
            'code'      => 'require|isNumber',
            // 'role'      => 'require',
//            'refferee'  => 'isPhone', //选填必填
        ];
        $validator = new UserValidator();

        //手动判断选填项目
        if ($params['refferee'] !== ''){
            if (!StringHelper::isPhoneNumber($params['refferee'])){
                throw new Exception(10100, '推荐人号码不符合格式');
            }
        }

        $validator->validate($params, $rules);
        $refferParam = [
            'page' => isset($_COOKIE["PAGE"]) ? $_COOKIE["PAGE"] : '',
            'http_referer' => isset($_COOKIE["HTTP_REFERER"]) ? $_COOKIE["HTTP_REFERER"] : '',
            'agent' => NetworkHelper::getUserAgent(),
            'os' => NetworkHelper::getUserOS(),
            'http_user_agent' => isset($_SERVER["HTTP_USER_AGENT"]) ? $_SERVER["HTTP_USER_AGENT"] : '',
        ];
        $rpcParams = [
            'mobile'    => $params['mobile'],
            'password'  => $params['password'],
            'code'      => $params['code'],
            'role'      => $params['role']?$params['role']:'',
            'method'    => $params['method'],
            'unionid'   => $params['unionid'],
            'ip'        => NetworkHelper::getClientIP(),
            'refferee' => $params['refferee'],
            'reffer_param' => $refferParam
        ];
        $rpcResult = YarService::create("/rpc/user", 'register', $rpcParams, $params['platform']);
        if ($rpcResult['code'] == 1) {
            return $rpcResult['data'];
        } else {
            throw new Exception(10189, $rpcResult['code'].'::'.$rpcResult['msg']);
        }
    }



}